package com.sjyp.cms.controller.admin;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.sjyp.cms.model.User;
import sun.security.provider.MD5;

import java.util.List;

/**
* 项目名称：   
* 类名称：LoginContrller 
* 类描述： 【登录管理】控制器
* 创建人：zangzh   
* 创建时间：  2015-6-30
* 修改人：zangzh   
* 修改时间：   
* 修改备注： 
* @version 1.0
 */
public class LoginContrller extends Controller {
	private static String LOGIN_PAGE = "login.html";
	private static String HOME_PAGE = "home.html";
	/**
	* Title: index
	* Description:进入登录页
	*/
	public void index() { 
		this.render("login.html");
	}

	/**
	 * 进入管理主界面
	 */
	public void home() {
		User loginUser = this.getSessionAttr("loginUser");
		if (null == loginUser) {
			User user = this.getBean(User.class, "");
			if (null == user || StrKit.isBlank(user.getUserName())) {
				this.setAttr("errorMsg", "用户名不能为空");
				this.render(LOGIN_PAGE);
			}
			if (StrKit.isBlank(user.getPassword())) {
				this.setAttr("errorMsg", "密码不能为空");
				this.render(LOGIN_PAGE);
			}
			List<User> users = User.dao.find("select * from t_user where userName=?", user.getUserName());
			boolean isSuccess = false;
			for (User u : users) {
				if (user.getPassword().equals(u.getPassword())) {
					isSuccess = true;
					user = u;
					break;
				}
			}
			if (isSuccess) {
				this.setSessionAttr("loginUser",user);
				this.render(HOME_PAGE);
			} else {
				this.setAttr("errorMsg", "密码错误").setAttr("userName", user.getUserName());
				this.render(LOGIN_PAGE);
			}
		} else {
			this.render(HOME_PAGE);
		}
	}

	public void loginOut() {
		this.removeSessionAttr("loginUser");
		this.render(LOGIN_PAGE);
	}
}
